import json

from django.core.cache import cache
from goods.models import GoodsChannelGroup

from urllib import parse
from urllib import request as re

def get_categories():
    data = cache.get('category_data')
    if data:
        return data

    data = {}
    channel_group_all = GoodsChannelGroup.objects.all()
    # 构建频道组数据
    for channel_group in channel_group_all:
        channel_group_data = {"channels": [], "sub_cats": []}
        data[channel_group.id] = channel_group_data
        # 添加频道信息
        channels = channel_group.goodschannel_set.all()
        for channel in channels:
            channel_data = {'id': channel.id, 'name': channel.category.name, 'url': channel.url}
            channel_group_data['channels'].append(channel_data)
            # 获取一级分类
            cat1 = channel.category
            # 遍历二级分类
            cat2_all = cat1.subs.all()
            for cat2 in cat2_all:
                cat2_data = {'id': cat2.id, 'name': cat2.name, 'sub_cats': []}
                channel_group_data['sub_cats'].append(cat2_data)

                # 遍历三级分类
                cat3_all = cat2.subs.all()
                for cat3 in cat3_all:
                    cat3_data = {'id': cat3.id, 'name': cat3.name}
                    cat2_data['sub_cats'].append(cat3_data)
    cache.set('category_data',data,3600*24)
    return data

def get_location(ip):
    ak = "Tt53SzYbchYDg5GSYYb5IfsVmedt4phq"
    url = "https://api.map.baidu.com/location/ip"
    data = {"ip": ip, "ak": ak, "coor": "bd09ll"}
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}
    data = parse.urlencode(data).encode()
    opener = re.build_opener()
    request = re.Request(url, data=data, headers=headers)
    response = opener.open(request, timeout=10)
    location_data = json.loads(response.read().decode("utf-8"))
    return location_data

def get_ip(request):
    '''获取请求者的IP信息'''
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
    return ip
